import { useEffect, useState } from "react";
import styles from "./MapContainer.module.css"
import AMapLoader from "@amap/amap-jsapi-loader";
import axios from "axios";
import {useSearchParams} from 'react-router-dom'

export default function MapContainer() {
  const [searchParams, setSearchParams] = useSearchParams()
  let dizhi = searchParams.get('dizhi')
  let map = null;
  const [address, setAddress] = useState('')
  const [center, setCenter] = useState("")
  const [latitude, setLatitude] = useState(null);
  const [longitude, setLongitude] = useState(null);
  const [lng, setLng] = useState(38)
  const [lat, setLat] = useState(115)

  useEffect(() => {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          // setLatitude(position.coords.latitude);
          // setLongitude(position.coords.longitude);
          console.log(position.coords.latitude, position.coords.longitude)
        },
        (error) => {
          console.error('Error getting geolocation:', error);
        }
      );
    } else {
      console.error('Geolocation is not supported by this browser.');
    }
    window._AMapSecurityConfig = {
      securityJsCode: "22c4e2bcf20b0696add3e62d78486e14",
    };
    AMapLoader.load({
      key: "acfbe2c88f6cf8ab998e0faa7c46a4aa", // 申请好的Web端开发者Key，首次调用 load 时必填
      version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      plugins: ["AMap.Scale", "AMap.ToolBar", "AMap.ControlBar", "AMap.HawkEye"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
    })
      .then((AMap) => {
        map = new AMap.Map("container", {
          resizeEnable: true, // 是否监控地图容器尺寸变化
          zoom: 12, //初始化地图层级
        });
        var autoOptions = {
          input: "tipinput"
        };
        AMap.plugin(['AMap.PlaceSearch', 'AMap.AutoComplete', 'AMap.Geolocation', "AMap.Driving",], function () {
          var auto = new AMap.AutoComplete(autoOptions);
          console.log(auto);
          
          var placeSearch = new AMap.PlaceSearch({
            map: map
          });  //构造地点查询类
          auto.on("select", select);//注册监听，当选中某条记录时会触发
          console.log(auto.on("select", select));
          
          function select(e) {
            // placeSearch.setCity(e.poi.adcode);
            placeSearch.search(e.poi.name);  //关键字查询查询
            console.log(e);
            setLat(e.poi.location.lat)
            setLng(e.poi.location.lng)
          }
          var driving = new AMap.Driving({
            map: map,
            panel: "panel"
          });
          var geolocation = new AMap.Geolocation({
            enableHighAccuracy: true,//是否使用高精度定位，默认:true
            timeout: 10000,          //超过10秒后停止定位，默认：5s
            position: 'RB',    //定位按钮的停靠位置
            offset: [10, 20], //定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
            zoomToAccuracy: true,   //定位成功后是否自动调整地图视野到定位点
            needAddress: true, //是否返回逆地理编码结果，默认：true
          });
          map.addControl(geolocation);
          geolocation.getCurrentPosition(function (status, result) {
            console.log(status, result);
            if (status == 'complete') {
              onComplete(result)
            } else {
              onError(result)
            }
          });

          var drivingOption = {
            policy: AMap.DrivingPolicy.LEAST_TIME, // 其它policy参数请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingPolicy
            //AMap.DrivingPolicy.LEAST_TIME, //最少时间
            //AMap.DrivingPolicy.LEAST_FEE, //最经济模式
            //AMap.DrivingPolicy.LEAST_DISTANCE, //最短距离模式
            //AMap.DrivingPolicy.REAL_TRAFFIC, //真实交通   考虑实时路况（仅适用于驾车导航）

            ferry: 1, // 是否可以使用轮渡
            // province: '冀', // 车牌省份的汉字缩写  
          }

          // 构造路线导航类
          var driving = new AMap.Driving(drivingOption)

          // 根据起终点经纬度规划驾车导航路线
          driving.search(new AMap.LngLat(longitude, latitude), new AMap.LngLat(lng, lat), function (status, result) {
            // result即是对应的驾车导航信息，相关数据结构文档请参考 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
            if (status === 'complete') {
              if (result.routes && result.routes.length) {
                // 绘制第一条路线，也可以按需求绘制其它几条路线
                drawRoute(result.routes[0])
                console.log("路线规划成功！");

              }
            } else {
              console.log("路线规划失败：" + result.info);

            }
          });

          function drawRoute(route) {
            var path = parseRouteToPath(route)

            var startMarker = new AMap.Marker({
              position: path[0],
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/start.png',
              map: map
            })

            var endMarker = new AMap.Marker({
              position: path[path.length - 1],
              icon: 'https://webapi.amap.com/theme/v1.3/markers/n/end.png',
              map: map
            })

            var routeLine = new AMap.Polyline({
              path: path,
              isOutline: true,
              outlineColor: '#ffeeee',
              borderWeight: 2,
              strokeWeight: 5,
              strokeOpacity: 0.9,
              strokeColor: '#0091ff',
              lineJoin: 'round'
            })

            map.add(routeLine);

            // 调整视野达到最佳显示区域
            map.setFitView([startMarker, endMarker, routeLine])


          }

          // 解析DrivingRoute对象，构造成AMap.Polyline的path参数需要的格式
          // DrivingResult对象结构参考文档 https://lbs.amap.com/api/javascript-api/reference/route-search#m_DriveRoute
          function parseRouteToPath(route) {
            var path = []

            for (var i = 0, l = route.steps.length; i < l; i++) {
              var step = route.steps[i]

              for (var j = 0, n = step.path.length; j < n; j++) {
                path.push(step.path[j])
              }
            }

            return path
          }
        });
        function onComplete(data) {
          console.log(data.formattedAddress);
          // map.setCenter(data);
          setLatitude(data.position.lat)
          setLongitude(data.position.lng)
          setAddress(data.formattedAddress)
        }
        //解析定位错误信息
        function onError(data) {
          console.log(data.message || '定位失败');

        }
        let data = axios.get(`https://restapi.amap.com/v3/geocode/geo?address=${center}&output=JSON&key=acfbe2c88f6cf8ab998e0faa7c46a4aa`)//通过地址获取经纬度
        console.log(data);

      })
      .catch((e) => {
        console.log(e);
      });
    return () => {
      map?.destroy();
    };
  }, [address, longitude, latitude, lat, lng]);

  return (
    <>
      <div
        id="container"
        className={styles.container}
      >
      </div>
      <div id="myPageTop">
        <table className={styles.over}>
          <thead>
            <tr>
              <td>
                <label>请输入关键字：</label>
              </td>
            </tr>
          </thead>

          <tbody>
            <tr>
              <td>
                <input id="tipinput" />
              </td>
            </tr>
          </tbody>

        </table>
        <div id="panel"></div>
      </div>
    </>


  );
}
